package cn.school.classManage.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import cn.school.classManage.dao.ClassTeacherRelationDao;
import cn.school.classManage.dao.SchoolClassDao;
import cn.school.classManage.service.SchoolClassService;
import cn.school.classManage.vo.ClassInfoExcelVo;
import cn.school.classManage.vo.ClassTeacherRelationVo;
import cn.school.classManage.vo.SchoolClassVO;
import cn.school.common.api.CommonPage;
import cn.school.common.api.CommonResult;
import cn.school.common.exception.ApiException;
import cn.school.common.utils.SysUserUtils;
import cn.school.course.service.CourseService;
import cn.school.educational.entity.Subject;
import cn.school.educational.vo.SubjectExcelVo;
import cn.school.notice.dao.FamilyNoticeDao;
import cn.school.notice.entity.FamilyNotice;
import cn.school.student.dao.StudentInfoDao;
import cn.school.student.entity.StudentInfo;
import cn.school.sys.entity.SysUser;
import cn.school.sys.entity.SysUserRole;
import cn.school.sys.service.SysUserRoleService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

@Service
public class SchoolClassServiceImpl extends ServiceImpl<SchoolClassDao, SchoolClassVO> implements SchoolClassService {
	@Autowired
	SchoolClassDao schoolClassDao;
	@Autowired
	private SysUserRoleService sysUserRoleService;
	@Autowired
	private StudentInfoDao studentInfoDao;
	
	@Autowired
	private FamilyNoticeDao familyNoticeDao;
	
	@Autowired
	private CourseService courseService;
	
	@Resource
	private ClassTeacherRelationDao teacherRelationDao;
	
	@Override
	public IPage<SchoolClassVO> findSchoolClassPageList(SchoolClassVO vo) {
		// 是否不过滤当前用户，班主任查询条件）
		boolean isAllowNotFilterCurrentUser = false;
		if (vo.getLoginUserId() != null) {
			// 传入登录用户ID，则要判断是否是教务、学工角色，如果则允许放开班级信息的筛选
			LambdaQueryWrapper<SysUserRole> userRoleQueryWrapper = new LambdaQueryWrapper<>();
			userRoleQueryWrapper.eq(SysUserRole::getTenantId, SysUserUtils.getSysUser().getTenantId());
			userRoleQueryWrapper.eq(SysUserRole::getUserId, vo.getLoginUserId());
			userRoleQueryWrapper.in(SysUserRole::getRoleId, new Long[]{1L, 5L, 10L});
			int count = sysUserRoleService.count(userRoleQueryWrapper);
			if (count != 0) {
				isAllowNotFilterCurrentUser = true;
			}
		}
		
		SysUser user = SysUserUtils.getSysUser();
//        List<SysUserRole> roleList = user.getRoleInfoList();
		//如果不是管理员则只能查当前登录人的数据
		List<SysUserRole> roleInfoList = SysUserUtils.getSysUser().getRoleInfoList();
		boolean isAdmin = false;
		for (SysUserRole sysUserRole : roleInfoList) {
			if ("超级管理员".equals(sysUserRole.getRoleName())) {
				isAdmin = true;
			}
		}
//        boolean isBanzhuren = roleList.stream().anyMatch(m->m.getRoleName().equals("班主任"));
		LambdaQueryWrapper<SchoolClassVO> wrapper = new LambdaQueryWrapper<>();
		if (!isAdmin) {
			wrapper.eq(SchoolClassVO::getClassTeacherId, user.getUsername());
		}
		
		if (!isAllowNotFilterCurrentUser && !StringUtils.isEmpty(vo.getClassTeacherId())) {
			wrapper.eq(SchoolClassVO::getClassTeacherId, vo.getClassTeacherId());
		}
		if (!StringUtils.isEmpty(vo.getClassName())) {
			wrapper.like(SchoolClassVO::getClassName, vo.getClassName());
		}
		if (!StringUtils.isEmpty(vo.getStatus())) {
			wrapper.eq(SchoolClassVO::getStatus, vo.getStatus());
		}
		if (!StringUtils.isEmpty(vo.getClassDept())) {
			wrapper.eq(SchoolClassVO::getClassDept, vo.getClassDept());
		}
		if (!StringUtils.isEmpty(vo.getIsGraduation())) {
			wrapper.eq(SchoolClassVO::getIsGraduation, vo.getIsGraduation());
		}
		if (!StringUtils.isEmpty(vo.getClassSubject())) {
			wrapper.eq(SchoolClassVO::getClassSubject, vo.getClassSubject());
		}
		wrapper.eq(SchoolClassVO::getTenantId, SysUserUtils.getSysUser().getTenantId());
		wrapper.orderByDesc(SchoolClassVO::getCreateTime);
		Page<SchoolClassVO> page = page(new Page<>(vo.getPageNum(), vo.getPageSize()), wrapper);
		
		// 设置班级的人数
		if (page.getRecords() != null && page.getRecords().size() != 0) {
			for (SchoolClassVO record : page.getRecords()) {
				LambdaQueryWrapper<StudentInfo> studentInfoWrapper = new LambdaQueryWrapper<>();
				studentInfoWrapper.eq(StudentInfo::getClassId, record.getId());
				studentInfoWrapper.eq(StudentInfo::getTenantId, SysUserUtils.getSysUser().getTenantId());
				Integer classPersonCount = this.studentInfoDao.selectCount(studentInfoWrapper);
				record.setPersonCount(classPersonCount);
			}
		}
		
		return page;
	}
	
	@Override
	public int addOrUpdateSchoolClassInfo(SchoolClassVO vo) {
		int num = 0;
		if (StringUtils.isEmpty(vo.getId())) {
			vo.setCreateTime(new Date());
			num = this.baseMapper.insert(vo);
		} else {
			vo.setModifyTime(new Date());
			num = this.baseMapper.updateById(vo);
		}
		return num;
	}
	
	@Override
	public int deleteSchoolClassInfo(Long id) {
		return this.baseMapper.deleteById(id);
	}
	
	@Override
	public List<SchoolClassVO> findAllSchoolClass() {
		return schoolClassDao.findAllSchoolClass(SysUserUtils.getSysUser().getTenantId());
	}
	
	@Override
	public List<SchoolClassVO> findClassByTeacher() {
		String teacherId = SysUserUtils.getSysUser().getUsername();
		return schoolClassDao.selectClassList(teacherId);
	}
	
	@Override
	public int batchUpdateClassStatus(List<SchoolClassVO> list) {
		int num = 0;
		for (SchoolClassVO vo : list) {
			schoolClassDao.updateById(vo);
			num++;
		}
		return num;
	}
	
	@Override
	public CommonPage<FamilyNotice> findAcsRecordByClassId(SchoolClassVO classVO) {
		// 查找出班级的信息
		LambdaQueryWrapper<SchoolClassVO> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(SchoolClassVO::getId, classVO.getId());
		SchoolClassVO schoolClassVO = schoolClassDao.selectOne(queryWrapper);
		if (Objects.isNull(schoolClassVO)) {
			return new CommonPage<>();
		}
		
		IPage<FamilyNotice> ipage = new Page<>();
		ipage.setCurrent(classVO.getPageNum());
		ipage.setSize(classVO.getPageSize());
		LambdaQueryWrapper<FamilyNotice> lambdaQueryWrapper = new LambdaQueryWrapper<>();
		lambdaQueryWrapper.eq(FamilyNotice::getStudentClass, classVO.getId());
		lambdaQueryWrapper.and((wrapper) -> {
			wrapper.eq(FamilyNotice::getType, 3).or().eq(FamilyNotice::getType, 4);
		});
		IPage<FamilyNotice> noticeIPage = familyNoticeDao.selectPage(ipage, lambdaQueryWrapper);
		if (CollectionUtil.isNotEmpty(noticeIPage.getRecords())) {
			noticeIPage.getRecords().forEach(familyNotice -> familyNotice.setStudentClass(schoolClassVO.getClassName()));
		}
		return CommonPage.restPage(noticeIPage);
	}
	
	@Override
	public SysUser queryByStudentName(Integer classId) {
		SysUser SysUser = this.schoolClassDao.queryByStudentName(classId);
		return SysUser;
	}
	
	@Override
	public SchoolClassVO findClassInfoByClassId(Long classId) {
		return this.baseMapper.selectById(classId);
	}
	
	@Override
	public List<SchoolClassVO> findClassInfo(SchoolClassVO classVO) {
		classVO.setTenantId(SysUserUtils.getSysUser().getTenantId());
		LambdaQueryWrapper<SchoolClassVO> wrapper = new LambdaQueryWrapper<>(classVO);
		return this.baseMapper.selectList(wrapper);
	}
	
	@Override
	@Transactional(rollbackFor = Exception.class)
	public int classTeacherConfig(List<ClassTeacherRelationVo> vos) {
		int num = 1;
		LambdaQueryWrapper<ClassTeacherRelationVo> delQueryWrapper = new LambdaQueryWrapper<>();
		delQueryWrapper.eq(ClassTeacherRelationVo::getClassId, vos.get(0).getClassId());
		List<ClassTeacherRelationVo> classTeacherRelationVos = teacherRelationDao.selectList(delQueryWrapper);
		teacherRelationDao.delete(delQueryWrapper);
		for (int i = 0; i < vos.size(); i++) {
			for (int o = i + 1; o < vos.size(); o++) {
				if (vos.get(i).getUserId().equals(vos.get(o).getUserId()) || vos.get(i).getSubjectId().equals(vos.get(o).getSubjectId())) {
					return num = 1;
				}
			}
			teacherRelationDao.insert(vos.get(i));
			num++;
		}


//        for (ClassTeacherRelationVo vo : vos) {
//            // 先查询看是否当前科目已经配置了教员
//            LambdaQueryWrapper<ClassTeacherRelationVo> queryWrapper = new LambdaQueryWrapper<>();
//            queryWrapper.eq(ClassTeacherRelationVo::getClassId, vo.getClassId()).and(wrapper -> {
//                wrapper.eq(ClassTeacherRelationVo::getUserId, vo.getUserId())
//                        .eq(ClassTeacherRelationVo::getSubjectId, vo.getSubjectId());
//            });
//            ClassTeacherRelationVo relationVo = teacherRelationDao.selectOne(queryWrapper);
//            if (Objects.nonNull(relationVo) && classTeacherRelationVos.size()>1) {
//                return -1;
//            }
//            teacherRelationDao.insert(vo);
//            num++;
//        }
		
		return num;
	}
	
	@Override
	public CommonResult<String> importClassInfoExcel(InputStream inputStream) throws IOException {
		XSSFWorkbook workbook = new XSSFWorkbook(inputStream);
		XSSFSheet sheetAt = workbook.getSheetAt(0);
		List<ClassInfoExcelVo> list = new ArrayList<>();
		ClassInfoExcelVo classInfoExcelVo = null;
		for (int i = 1; i < sheetAt.getPhysicalNumberOfRows(); i++) {
			Row row = sheetAt.getRow(i);
			classInfoExcelVo = new ClassInfoExcelVo();
			if (i > 1) {
				for (int j = 0; j < row.getLastCellNum(); j++) {
					Cell cell = row.getCell(j);
					if (j == 0) {
						classInfoExcelVo.setClassName(cell.getStringCellValue());
					}
					if (j == 1) {
						System.out.println(cell.getStringCellValue());
						classInfoExcelVo.setClassGrade(cell.getStringCellValue());
					}
				}
				list.add(classInfoExcelVo);
			}
		}
		if (CollectionUtil.isEmpty(list)) {
			throw new ApiException("班级信息为空，请按模版填写需要导入的班级信息");
		}
		int row = insertClassInfo(list);
		if (row > 0) {
			return CommonResult.success();
		}
		return CommonResult.failed();
	}
	
	private int insertClassInfo(List<ClassInfoExcelVo> vo) {
		int num = 0;
		SchoolClassVO classVO = null;
		for (int j = 0; j < vo.size(); j++) {
			LambdaQueryWrapper<SchoolClassVO> classVOLambdaQueryWrapper = new LambdaQueryWrapper<>();
			if (StrUtil.isNotEmpty(vo.get(j).getClassName())) {
				classVOLambdaQueryWrapper.eq(SchoolClassVO::getClassName, vo.get(j).getClassName());
				int count = this.baseMapper.selectCount(classVOLambdaQueryWrapper);
				if (count > 0) {
					throw new ApiException("班级名称:"+ vo.get(j).getClassName() + "出现重复，请检查班级名称");
				}
			}
		}
		for (int i = 0; i < vo.size(); i++) {
			classVO = new SchoolClassVO();
			classVO.setClassName(vo.get(i).getClassName());
			classVO.setClassGrade(vo.get(i).getClassGrade());
			classVO.setCreateTime(Calendar.getInstance().getTime());
			classVO.setModifyTime(Calendar.getInstance().getTime());
			// classVO.setCreateBy(SysUserUtils.getSysUser().getId());
			int row = baseMapper.insert(classVO);
			if (row > 0) {
				num += 1;
			}
		}
		if (num < vo.size()) {
			return num = 0;
		}
		return num;
	}
}
